<template>
  <!-- 添加同住人弹窗 -->
  <el-dialog title="添加同住人" :model-value="visible" width="550px" :fullscreen="mobile" @close="handleCancel">
    <el-form :model="cohabitantsForm" ref="cohabitantsFormRef" :rules="cohabitantsRules" label-width="80px">
      <el-row>
        <el-col :span="22">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="cohabitantsForm.name" placeholder="请输入姓名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="22">
          <el-form-item label="联系方式" prop="contacts">
            <el-input v-model="cohabitantsForm.contacts" placeholder="请输入联系方式"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="证件号" prop="idCardNumber">
            <el-input v-model="cohabitantsForm.idCardNumber" placeholder="请输入证件号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-icon class="mt10 ml10"><Wallet /></el-icon>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleOk">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup name="CohabitantsDl">
import useAppStore from '@/store/modules/app'
import { nextTick } from 'vue'

const { proxy } = getCurrentInstance()

const emit = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean
  },
  type: {
    type: String
  },
  form: {
    type: Object,
    default: () => {}
  }
})

const mobile = computed(() => useAppStore().device === 'mobile')
const data = reactive({
  cohabitantsForm: {
    name: undefined,
    contacts: undefined,
    idCardNumber: undefined,
  },
  cohabitantsRules: {
    name: [{ required: true, message: "请输入名字", trigger: "blur" }],
    contacts: [{ required: true, pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],
  },
})
const { cohabitantsForm, cohabitantsRules } = toRefs(data)
watch(() => props.visible, (value) => {
  if (value) {
    nextTick(() => {
      proxy.resetForm('cohabitantsFormRef')
      if (props.type === 'edit') {
        cohabitantsForm.value = { ...props.form }
      }
    })
  }
})

function handleCancel() {
  emit('cancel')
}
function handleOk() {
  proxy.$refs['cohabitantsFormRef'].validate(valid => {
    if (valid) {
      emit('ok', props.type, cohabitantsForm.value)
    }
  })
}
</script>
